package com.example.browser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by dhs on 2018/7/27.
 */

public class jsstate extends Activity {
    private ListView lv;
    private MyDatabaseHelper dbHelper;



    private static final String FILENAME="YX";
    private String get_title,get_url,get_state;//暂存从数据库得到的title和url
    private int get_id; //暂存从数据库得到的id
    private String titler, url,js;//按值查找详细信息
    int id; //按值查找id
    private TextView text_title, text_url,text_state,text_js;//书签详细信息edittext
    private ArrayList arrayList=new ArrayList();

    private boolean if_exist;

    private Button addjs;




    private EditText search_jsstate;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_jssate);
        getWindow().setGravity(Gravity.BOTTOM);//底部出现
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);//设置弹窗宽高


        lv=(ListView)findViewById(R.id.bookmark_list);
        search_jsstate=(EditText)findViewById(R.id.search_bookmark) ;
        //监听编辑框
        search_jsstate.addTextChangedListener(new EditChangedListener());
        queryinfo();
        onclick();




    }

    private void onclick() {


        //点击函数：
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (if_exist) {
                    new AlertDialog.Builder(jsstate.this)
                            .setItems(new String[]{"停用", "启用","删除","修改"}, (dialog, which) -> {

                                switch (which) {
                                    case 0:
                                        state_stop(query_by_id2(position));
                                        break;
                                    case 1:
                                        state_start(query_by_id2(position));
                                        break;
                                    case 2:
                                        delete_dialog(position);
                                        break;
                                    case 3:
                                        url_infomation(position);
                                        break;
                                }
                            })
                            .show();
                }
            }
        });
        //长按选择删除
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (if_exist)
                    new AlertDialog.Builder(jsstate.this)
                            .setItems(new String[]{"停用", "启用","删除","修改"}, (dialog, which) -> {

                                switch (which) {
                                    case 0:
                                        state_stop(query_by_id2(position));
                                        break;
                                    case 1:
                                        state_start(query_by_id2(position));
                                        break;
                                    case 2:
                                        delete_dialog(position);
                                        break;
                                    case 3:
                                        url_infomation(position);
                                        break;
                                }
                            })
                            .show();
                return true;
            }
        });
    }











    //jsstateDB删除函数：
    public void delete(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("jstoolDB","id=?",new String[] {String.valueOf(arrayList.get(position))});
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        // arrayList.clear();
        queryinfo();


    }

    //全部删除
    public void delete_all(){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from jsstateDB", null);
        while (cursor.moveToNext()) {
            id=cursor.getInt(0);
            db.delete("jstoolDB","id=?",new String[] {String.valueOf(id)});
        }
        cursor.close();
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        //arrayList.clear();
        //刷新UI
        queryinfo();
    }
    //jsstateDB全部删除对话框
    public void delete_dialog(int position){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定全部删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete(position);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    //jsstateDB全部删除对话框
    public void delete_all_dialog(){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定全部删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete_all();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    //数据库逆序查询函数：
    public void queryinfo(){
        arrayList.clear();
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql ="SELECT * FROM jstoolDB WHERE state='已启用'";
        Cursor cursor=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);
                get_url = cursor.getString(2);
                get_state=cursor.getString(4);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("title", get_title);
                map.put("url", get_url);
                map.put("state", get_state);
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem, R.layout.jstoolzujian,
                        new String[] {"title","url","state"},
                        new int[] {R.id.title, R.id.url, R.id.state});
                lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }
        else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("title", "暂无");
            map.put("url", "");
            map.put("state","");
            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem, R.layout.bookmarkzujian,
                    new String[] {"title","url","state"},
                    new int[] {R.id.title, R.id.url, R.id.state});
            lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }

        cursor.close();
        db.close();
    }
    //按值查找：
    public String query_by_id(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from jstoolDB", null);
        while (cursor.moveToNext()) {
            js=cursor.getString(3);
            url = cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return url;
    }
    public int query_by_id2(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from jstoolDB", null);
        while (cursor.moveToNext()) {
            js=cursor.getString(3);
            url = cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return id;
    }

    //修改数据
    public void update(int id, String title, String url,String js) {
        //字符串过长只能使用db.update
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", title);
        values.put("url", url);
        values.put("js",js);
        values.put("state","已启用");
        //insert（）方法中第一个参数是表名，第二个参数是表示给表中未指定数据的自动赋值为NULL。第三个参数是一个ContentValues对象
        db.update("jstoolDB",values,"id="+id,null);
        db.close();
        Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show();
        queryinfo();
    }
    //启动Js
    public void state_start(int id) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql="update jstoolDB set state='已启用' where id="+ id;
        db.execSQL(sql);
        db.close();
        queryinfo();
    }
    //停止Js
    public void state_stop(int id) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql="update jstoolDB set state='已停用' where id="+ id;
        db.execSQL(sql);
        db.close();
        queryinfo();
    }
    //url详细信息对话框
    public void url_infomation(final int position){
        final Dialog dialog = new Dialog(jsstate.this, R.style.MyDialogActivityStyle);
        View view = View.inflate(jsstate.this, R.layout.dialog_addjs, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window window = dialog.getWindow();//得到对话框的窗口．
        WindowManager.LayoutParams wl = window.getAttributes();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
        wl.width = (int)(display.getWidth() * 1); //设置宽度
        wl.height = (int)(display.getHeight() * 0.4);
        wl.alpha = 1f;// 设置对话框的透明度,1f不透明
        window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
        window.setAttributes(wl);
        text_title = (EditText) view.findViewById(R.id.title);
        text_url = (EditText) view.findViewById(R.id.url);
        text_js= (EditText) view.findViewById(R.id.js);
        text_title.setFocusable(true);
        text_title.setFocusableInTouchMode(true);
        text_title.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(text_title, 0);
                           }
                       },
                200);

        //显示详细信息
        text_url.setText(query_by_id(position));
        text_title.setText(titler);
        text_js.setText(js);
        view.findViewById(R.id.addweb).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                update(query_by_id2(position),text_title.getText().toString(),text_url.getText().toString(),text_js.getText().toString());
                //刷新UI
                queryinfo();
                dialog.dismiss();

            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.show();


    }



    //数据库逆序查询函数：
    public void queryinfo2( String url ){
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        arrayList.clear();
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";

        String sql = "select * from jstoolDB where url like '%"+ url + "%'OR title like '%"+ url + "%'";
        Cursor cursor=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);
                get_url = cursor.getString(2);
                get_state=cursor.getString(3);
                HashMap<String, Object> map = new HashMap<String, Object>();
                if(get_state.equals("已启用")){
                    map.put("title", get_title);
                    map.put("url", get_url);
                    map.put("state", get_state);
                    arrayList.add(get_id);
                    listItem.add(map);
                    //new String  数据来源， new int 数据到哪去
                    SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem, R.layout.jstoolzujian,
                            new String[] {"title","url","state"},
                            new int[] {R.id.title, R.id.url, R.id.state});
                    lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
                }
            }
        }
        else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("title", "没有找到");
            map.put("url", "");
            map.put("state","");
            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem, R.layout.jstoolzujian,
                    new String[] {"title","url","state"},
                    new int[] {R.id.title, R.id.url, R.id.state});
            lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }

        cursor.close();
        db.close();
    }


    //监听编辑框--https://www.jb51.net/article/135392.htm
    //https://blog.csdn.net/ycwol/article/details/46594275
    class EditChangedListener implements TextWatcher {
        public void afterTextChanged(Editable arg0) {
// 文字改变后出发事件
            String content = search_jsstate.getText().toString();
            //若输入框内容为空按钮可点击，字体为蓝色
            if (!content.isEmpty()) {
                queryinfo2(search_jsstate.getText().toString());

            } else {
                queryinfo();

            }

        }
        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
// TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub

        }
    };

    //获取返回搜索url
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if(resultCode==1){

                // int resultid=Integer.parseInt(data.getStringExtra("move"));
                // deleteid(resultid);


            }
        }

    }





    @Override
    protected void onRestart() {
        super.onRestart();
        //刷新UI
        queryinfo();

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        finish();//点击窗口外部区域 弹窗消失
        return true;
    }



}